import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useTabsStore = defineStore('tabs', () => {
  const tabsExist = ref([])
  const activeTab = ref('')

  const addTab = (title, path) => {
    tabsExist.value.push({
      title,
      name: path
    })
    activeTab.value = path
  }

  const removeTab = (targetName) => {
    const tabs = tabsExist.value
    let activeName = activeTab.value
    if (activeName === targetName) {
      tabs.forEach((tab, index) => {
        if (tab.name === targetName) {
          const nextTab = tabs[index + 1] || tabs[index - 1]
          if (nextTab) {
            activeName = nextTab.name
          }
        }
      })
    }
    activeTab.value = activeName
    tabsExist.value = tabs.filter((tab) => tab.name !== targetName)
  }

  return {
    tabsExist,
    activeTab,
    addTab,
    removeTab
  }

})